<script setup lang="ts">
import {ref, defineAsyncComponent, onMounted, onUnmounted, computed} from 'vue';
import {ctaDownloadWechat, ctaStatusInfo} from "@/api/cta";

import axios from "axios";
import {type CtaType} from "@/api/cta";
import {useRoute} from "vue-router";
import { logRecord } from "@/api/content";




const props = defineProps({
  omniUserUuid: {
    type: String,
    required: true
  },
  ctaType: {
    type: String,
    required: true
  },
  ctaUuid: {
    type: String,
    required: true
  },
  sceneType: {
    type: String,
    required: true
  },
  sceneUuid: {
    type: String,
    required: true
  },
  ctaShow: {
    type: Boolean,
    default: false
  },
  fileName: {
    type: String,
    default: ""
  },
  downloadType:{
    type:String,
    default: "file"
  },
  downloadLink:{
    type:String,
    default: ""
  }
});

const ctaType = ref<CtaType>(<"form" | "wechat_qrcode" | "work_qrcode">props.ctaType);
const ctaUuid = ref<string>(props.ctaUuid);
const ctaShow = ref(false);
const ctaEmailShow = ref(false);
const downloadLoading = ref(false);
const ctaStatus = ref(false);

const route = useRoute();
const customerUuid = route.params.customerUuid as string;
const aggListUuid = route.params.aggListUuid as string;
const pushId = route.query.pushId as string;
const identityType = localStorage.getItem('identity_type') as string;


onMounted(() => {
  console.log("onMounted")
});


const handleDownload = () => {
  getCtaStatus()
};

const initiateDownload = async () => {
  downloadLoading.value = true;
  if(props.downloadType === "link"){
    await logRecordAction("content_copy_link");
    window.location.href = props.downloadLink
    //copyText(props.downloadLink)
  }else{
    await logRecordAction("content_download");
    if (identityType !== 'canvas_id') {
      await downloadFileWechat();
    } else {
      await downloadFileH5();
    }
  }
  downloadLoading.value = false;
};



const handleCtaStatusUpdate = (val: boolean, isDownload: boolean) => {
  ctaStatus.value = val;
  ctaShow.value = false;
  if (isDownload) initiateDownload();
};

const componentOptions = {
  form : defineAsyncComponent(() => import("@/views/components/cta/CtaForm.vue")),
  work_qrcode : defineAsyncComponent(() => import("@/views/components/cta/CtaWork.vue")),
  wechat_qrcode : defineAsyncComponent(() => import("@/views/components/cta/CtaWechat.vue")),
};
const ctaEmailComponent = defineAsyncComponent(() => import("@/views/components/cta/CtaEmail.vue"))
const currentComponentComponent = computed(() => {
  if(ctaType.value){
    return componentOptions[ctaType.value];
  }else {
    return null;
  }
});



const handleSendEmail = ()=>{
  ctaEmailShow.value = true;
}


const getCtaStatus = async () => {
  try {
    const response = await ctaStatusInfo({
      omni_user_uuid: props.omniUserUuid,
      cta_uuid: props.ctaUuid,
      scene_type: props.sceneType,
      scene_uuid: props.sceneUuid
    });
    if(response.data.status){
      //直接下载
      await initiateDownload();
    }else{
      ctaShow.value = true;
    }
  } catch (e) {
    console.error(e);
  }
}





const downloadFileWechat = async () => {
  try {
    const response = await ctaDownloadWechat({ omni_user_uuid: props.omniUserUuid, cta_uuid: ctaUuid.value });
    if (response.data?.url) {
      window.location.href = response.data.url;
    }
  } catch (error) {
    console.error('下载微信文件时出错:', error);
  }
};


const downloadFileH5 = async () => {
  try {
    const response = await axios.post('/api/open/resource/content/download', {
      content_uuid: props.sceneUuid
    }, {
      headers: { 'customerUUID': customerUuid },
      responseType: 'blob'
    });
    const blob = new Blob([response.data], { type: response.headers['content-type'] || 'application/octet-stream' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `${props.fileName}.pdf`);
    document.body.appendChild(link);
    link.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(link);
  } catch (error) {
    console.error('下载文件时出错:', error);
  }
};

const logRecordAction = async (action_code: string) => {
  try {
    await logRecord({
      omni_user_uuid: props.omniUserUuid,
      action_code,
      entity_id: props.sceneUuid,
      extra_data: {
        content_uuid: props.sceneUuid,
        agg_list_uuid: aggListUuid
      },
      push_uuid:pushId
    });
  } catch (error) {
    console.error('记录日志时出错:', error);
  }
};


onUnmounted(() => {
  console.log("onUnmounted")
});


</script>

<template>
  <van-tabbar active-color="#ee0a24" class="flex items-center justify-around pb-2 pt-2">
    <van-button class="w-48" @click="handleSendEmail">
      发送到邮箱
    </van-button>
    <van-button color="#333333" type="primary" class="w-48" @click="handleDownload" :loading="downloadLoading" loading-text="下载中...">
      点击下载
    </van-button>
  </van-tabbar>

  <component
      v-if="ctaUuid && ctaShow && currentComponentComponent"
      v-model:ctaShow="ctaShow"
      :omniUserUuid="omniUserUuid"
      :ctaType="ctaType"
      :ctaUuid="ctaUuid"
      :sceneType="sceneType"
      :sceneUuid="sceneUuid"
      @updateCtaShow="ctaShow = false"
      @updateCtaStatus="handleCtaStatusUpdate"
      :is="currentComponentComponent"/>

  <component
      v-if="ctaUuid && ctaEmailShow"
      v-model:ctaShow="ctaEmailShow"
      :omniUserUuid="omniUserUuid"
      :ctaType="ctaType"
      :ctaUuid="ctaUuid"
      :sceneType="sceneType"
      :sceneUuid="sceneUuid"
      @updateCtaShow="ctaEmailShow = false"
      :is="ctaEmailComponent"/>

</template>


<style scoped>
</style>
